package ULHT.LIG2N1.RC.CLIENTINTERFACE;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Home extends javax.swing.JFrame implements Runnable {

    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private int timeout;

    public Home(Socket ds) throws IOException {

        this.socket = ds;
        in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        out = new PrintWriter(this.socket.getOutputStream(), true);
        initComponents();

        JFrame jFrame = new JFrame();

        jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    private String readFromServer() throws IOException {
        int msgSize = 0;
        String serverReply = null;
        char[] buffer = null;
        boolean isReplying = false;
        int i = 1;
        while (!isReplying && (i <= 10)) {
            try {
                serverReply = in.readLine();
            } catch (IOException ex) {
                i++;
            }
            if (serverReply != null && serverReply.length() > 0) {
                if (serverReply.isEmpty()) {
                    return null;
                } else {
                    try {
                        msgSize = Integer.parseInt(serverReply);
                    } catch (NumberFormatException nfe) {
                        return null;
                    }
                    buffer = new char[msgSize];
                    int totalRead = 0;
                    while (totalRead < msgSize) {
                        int read = 0;
                        try {
                            read = in.read(buffer, totalRead, msgSize - totalRead);
                        } catch (IOException ex) {
                            Logger.getLogger(MenuPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        if (read == -1) {
                            return null;
                        }
                        totalRead += read;
                    }
                    isReplying = true;
                }
            }
        }
        return new String(buffer);
    }

    private void writeToServer(String output) {
        if (!socket.isClosed()) {
            out.println(output);
        }
    }

    public void SetPergunta(String pergunta) {
        jTextArea3.setText(pergunta);
    }

    public String getNextQuestion() {

        String teste = "";
        int result = 0;
        try {
            teste = this.readFromServer();

            if (teste.equalsIgnoreCase("DISQUALIFIED")) {
                readFromServer();
                result = JOptionPane.showConfirmDialog(this, readFromServer(), "Mensagem do Servidor", JOptionPane.DEFAULT_OPTION);
                this.setVisible(false);
                return null;
            } else if (teste.equalsIgnoreCase("GAMEEND")) {
                result = JOptionPane.showConfirmDialog(this, readFromServer(), "Mensagem do Servidor", JOptionPane.DEFAULT_OPTION);
                this.setVisible(false);
                return null;
            } else {

                this.writeToServer("READY");
                this.timeout = Integer.parseInt(this.readFromServer());
                writeToServer("GETQUESTION");
                System.out.println(this.readFromServer());
                writeToServer("READY");

                return readFromServer();
            }
        } catch (IOException ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton9 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        opcaoC = new javax.swing.JButton();
        opcaoB = new javax.swing.JButton();
        opcaoD = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextArea();
        opcaoA = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        jButton9.setText("B");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.setToolTipText("");
        jPanel2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        opcaoC.setText("C");
        opcaoC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcaoCActionPerformed(evt);
            }
        });
        jPanel2.add(opcaoC, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 690, 369, 40));

        opcaoB.setText("B");
        opcaoB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcaoBActionPerformed(evt);
            }
        });
        jPanel2.add(opcaoB, new org.netbeans.lib.awtextra.AbsoluteConstraints(592, 610, 370, 40));

        opcaoD.setText("D");
        opcaoD.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcaoDActionPerformed(evt);
            }
        });
        jPanel2.add(opcaoD, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 690, 370, 40));

        jTextArea3.setBackground(new java.awt.Color(0, 0, 0));
        jTextArea3.setColumns(20);
        jTextArea3.setFont(new java.awt.Font("Monospaced", 0, 18)); // NOI18N
        jTextArea3.setForeground(new java.awt.Color(255, 255, 255));
        jTextArea3.setRows(5);
        jTextArea3.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextArea3.setEnabled(false);
        jScrollPane3.setViewportView(jTextArea3);

        jPanel2.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 80, 800, 280));

        opcaoA.setText("A");
        opcaoA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                opcaoAActionPerformed(evt);
            }
        });
        jPanel2.add(opcaoA, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 610, 370, 40));
        jPanel2.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 30, 100, 20));

        jLabel2.setBackground(new java.awt.Color(255, 255, 255));
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Nível");
        jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 30, 100, -1));

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });
        jPanel2.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 30, 100, 20));

        jLabel3.setBackground(new java.awt.Color(255, 255, 255));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Tempo Acumulado");
        jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 30, 100, -1));
        jPanel2.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 30, 100, 20));

        jLabel4.setBackground(new java.awt.Color(255, 255, 255));
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Pontos Acumulados");
        jPanel2.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 30, 100, -1));

        jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\luis.ferreira\\Desktop\\Untitled.jpg")); // NOI18N
        jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 740));

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void opcaoCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_opcaoCActionPerformed
        this.writeToServer("C");
        int result = 0;

        try {
            result = JOptionPane.showConfirmDialog(this, readFromServer(), "Resultado", JOptionPane.DEFAULT_OPTION);
        } catch (IOException ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (result == 0) {
            jTextArea3.setText(this.getNextQuestion());
        }
    }//GEN-LAST:event_opcaoCActionPerformed

    private void opcaoDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_opcaoDActionPerformed
        this.writeToServer("D");
        int result = 0;

        try {
            result = JOptionPane.showConfirmDialog(this, readFromServer(), "Resultado", JOptionPane.DEFAULT_OPTION);
        } catch (IOException ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (result == 0) {
            jTextArea3.setText(this.getNextQuestion());
        }
    }//GEN-LAST:event_opcaoDActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    }//GEN-LAST:event_jButton9ActionPerformed

    private void opcaoBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_opcaoBActionPerformed
        this.writeToServer("B");
        int result = 0;

        try {
            result = JOptionPane.showConfirmDialog(this, readFromServer(), "Resultado", JOptionPane.DEFAULT_OPTION);
        } catch (IOException ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (result == 0) {
            jTextArea3.setText(this.getNextQuestion());
        }
    }//GEN-LAST:event_opcaoBActionPerformed

    private void opcaoAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_opcaoAActionPerformed
        this.writeToServer("A");
        int result = 0;

        try {
            result = JOptionPane.showConfirmDialog(this, readFromServer(), "Resultado", JOptionPane.DEFAULT_OPTION);
        } catch (IOException ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (result == 0) {
            jTextArea3.setText(this.getNextQuestion());
        }
    }//GEN-LAST:event_opcaoAActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton9;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JButton opcaoA;
    private javax.swing.JButton opcaoB;
    private javax.swing.JButton opcaoC;
    private javax.swing.JButton opcaoD;
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
